<template>
  <div class="app-container">
    <div class="filter-container">
      <el-cascader
        v-model="listQuery.class_id"
        class="filter-item"
        style="width:30%"
        :options="class_options"
        @change="getList"
        clearable></el-cascader>
      <el-input v-model="listQuery.title" placeholder="关键字搜索" style="margin-left:10px;width: 200px;" class="filter-item"  />

      <el-select v-model="listQuery.ext" clearable placeholder="请选择" style="margin-left:10px;width: 200px;" class="filter-item" @change="getList">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-date-picker
        class="filter-item"
        style="margin-left:10px;"
        v-model="listQuery.time"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="getList"
        align="right">
      </el-date-picker>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-divider></el-divider>
      <el-select v-model="listQuery.special_id" filterable placeholder="专题合同列表" class="filter-item"
                 clearable @change="getList"
      >
        <el-option
          v-for="item in specialList"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select v-model="listQuery.banner_special_id" filterable placeholder="广告位专题" class="filter-item"
                 clearable @change="getList" style="margin-left:10px"
      >
        <el-option
          v-for="item in specialList"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <el-radio-group v-model="listQuery.type" @change="getList" class="filter-item" style="margin-left: 10px">
        <el-radio-button label="id">时间</el-radio-button>
        <el-radio-button label="download">下载量</el-radio-button>
        <el-radio-button label="png_count">页数</el-radio-button>
      </el-radio-group>
      <el-radio-group v-model="listQuery.sort_type" @change="getList" class="filter-item" style="margin-left: 20px">
        <el-radio-button type="success" label="asc">升序</el-radio-button>
        <el-radio-button type="success" label="desc">降序</el-radio-button>
      </el-radio-group>
      <el-radio-group v-model="listQuery.status" @change="getList" class="filter-item" style="margin-left: 20px">
        <el-radio label="success">成功</el-radio>
        <el-radio label="error">失败</el-radio>
      </el-radio-group>
      <el-button class="filter-item" type="success" style="float:right;margin-right:10px" @click="handleClickExport">导出excel
      </el-button>
      <el-button class="filter-item" style="float:right;margin-right:10px" type="primary" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" type="success" @click="get_ocpc"
                 style="float:right;margin-right:10px"
      >
        绑定专题
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width:100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="标题" min-width="180px" align="center">
        <template slot-scope="{row}">
          <el-link type="success" @click="toUrl(row.id)">{{ row.title }}</el-link>
        </template>
      </el-table-column>

<!--      &lt;!&ndash;        <el-table-column label="类型" class-name="status-col" min-width="100">&ndash;&gt;-->
<!--      &lt;!&ndash;          <template slot-scope="{row}">&ndash;&gt;-->
<!--      &lt;!&ndash;           <el-tag  v-if="row.type == 2" size="small">首页轮播图</el-tag>&ndash;&gt;-->
<!--      &lt;!&ndash;           <el-tag  v-else size="small">新闻轮播图</el-tag>&ndash;&gt;-->
<!--      &lt;!&ndash;          </template>&ndash;&gt;-->
<!--      &lt;!&ndash;        </el-table-column>&ndash;&gt;-->
      <el-table-column label="封面图" min-width="80" align="center">
        <template slot-scope="{row}">
          <el-tooltip content="点击放大" placement="right" effect="light">
            <el-image
              style="width: 50px; height: 50px"
              :src="row.title_pic"
              lazy
              fit="contain"
              @click="showBanner(row.title_pic)"
            ></el-image>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="预览" min-width="80px" align="center">
        <template slot-scope="{row}">
          <el-image
            style="width: 50px; height: 50px"
            :src="row.png[0]"
            :preview-src-list="row.png">
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="文件大小" min-width="80px" align="center">
        <template slot-scope="{row}">
           {{ row.size }}
        </template>
      </el-table-column>

      <el-table-column label="后缀" min-width="80px" align="center">
        <template slot-scope="{row}">
          {{ row.ext }}
        </template>
      </el-table-column>

      <el-table-column label="页数" min-width="80px" align="center">
        <template slot-scope="{row}">
          {{ row.png_count }}
        </template>
      </el-table-column>

      <el-table-column label="下载量" min-width="80px" align="center">
        <template slot-scope="{row}">
          {{ row.download }}
        </template>
      </el-table-column>

<!--&lt;!&ndash;      <el-table-column label="手机端图" min-width="80px" align="center">&ndash;&gt;-->
<!--&lt;!&ndash;        <template slot-scope="{row}">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-tooltip content="点击放大" placement="right" effect="light">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-image&ndash;&gt;-->
<!--&lt;!&ndash;              style="height:60px"&ndash;&gt;-->
<!--&lt;!&ndash;              :src="row.wap_thumb"&ndash;&gt;-->
<!--&lt;!&ndash;              fit="contain"&ndash;&gt;-->
<!--&lt;!&ndash;              @click="showBanner(row.wap_url)"&ndash;&gt;-->
<!--&lt;!&ndash;            ></el-image>&ndash;&gt;-->
<!--&lt;!&ndash;          </el-tooltip>&ndash;&gt;-->
<!--&lt;!&ndash;        </template>&ndash;&gt;-->
<!--&lt;!&ndash;      </el-table-column>&ndash;&gt;-->
      <el-table-column label="推送" class-name="status-col" min-width="80">
        <template slot-scope="{row}">
          <span v-if="row.is_push == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="banner位专题" class-name="status-col" min-width="120">
        <template slot-scope="{row}">
            {{row.special_name | ellipsis}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" class-name="status-col" min-width="100">
        <template slot-scope="{row}">
          <span>{{ row.created_at }}</span>
        </template>
      </el-table-column>
<!--      &lt;!&ndash;        <el-table-column label="更新时间" class-name="status-col" min-width="100">&ndash;&gt;-->
<!--      &lt;!&ndash;          <template slot-scope="{row}">&ndash;&gt;-->
<!--      &lt;!&ndash;            <span>{{ row.updated_at }}</span>&ndash;&gt;-->
<!--      &lt;!&ndash;          </template>&ndash;&gt;-->
<!--      &lt;!&ndash;        </el-table-column>&ndash;&gt;-->
      <el-table-column label="制图" align="center" min-width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleMakePng(row)">预览图<i class="el-icon-upload el-icon--right"></i></el-button>
          <el-button type="primary" size="mini" @click="handleMake(row)">缩略图<i class="el-icon-upload el-icon--right"></i></el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="130" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">
          </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row,$index)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-drawer
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      direction="ltr"
      >
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
      style="margin-left: 20px;padding:20px"
      >
        <el-form-item label="专题合同列表">
          <el-select v-model="temp.special_id" filterable placeholder="专题合同列表" class="filter-item"
                     clearable
          >
            <el-option
              v-for="item in specialList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专题广告位">
          <el-select v-model="temp.banner_special_id" filterable placeholder="专题广告位" class="filter-item"
                     clearable
          >
            <el-option
              v-for="item in specialList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader
          v-model="edit_class"
          class="filter-item"
          style="width:85%"
          :options="class_options"
          @change="changeClass($event)"
          clearable></el-cascader>
        </el-form-item>
        <el-form-item label="文件" v-if="dialogStatus==='create'">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :action="'/api/upload/upload_oss?class_id='+ JSON.stringify(edit_class)+'&special_id='+temp.special_id"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-change = "handleChange"
            :on-error = "handleError"
             multiple
            :file-list="fileList"
            :limit="50"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传docx/pdf文件，且不超过10M</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="标题" prop="label" v-if="dialogStatus==='update'">
          <el-input v-model="temp.title"/>
        </el-form-item>

        <el-form-item label="下载量" prop="label" v-if="dialogStatus==='update'">
          <el-input v-model="temp.download"/>
        </el-form-item>


        <el-form-item label="description" prop="label" v-if="dialogStatus==='update'">
         <font color="#a9a9a9">
          <span
            v-html="description">
          </span>
         </font>
        </el-form-item>
      </el-form>
      <center>
        <div slot="footer" class="dialog-footer" v-if="dialogStatus==='update'" >
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="updateData()">
            确认
          </el-button>
        </div>
      </center>
    </el-drawer>

    <el-dialog :visible.sync="dialogBannerVisible" width="80%">
      <center>
        <el-image fit="contain" :src="showBannerUrl" width="100%"></el-image>
      </center>
    </el-dialog>


    <el-dialog title="绑定专题广告" :visible.sync="dialogFormVisible1" width="40%">
      <el-divider><span v-if="total">当前搜索结果--{{total}}条</span></el-divider>
      <el-form  label-position="left" label-width="120px"
               style="width: 80%; margin-left:10%;"
      >
        <el-form-item label="专题广告位">
          <el-select v-model="banner_special_id" filterable placeholder="广告位专题" class="filter-item"
                     clearable style="margin-left:10px"
          >
            <el-option
              v-for="item in specialList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button type="success" @click="bindSpecial">
            确认绑定
          </el-button>
        </center>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, update, del, makePic, makePng, bindSpecial } from '@/api/contract'
import { getAll } from '@/api/special'
import Pagination from '@/components/Pagination'
import { getClass, parentClass ,getNewClass} from '@/api/contract_class'
import { getStatus } from '@/api/color'
import { formatMoney } from '@/api/util'
export default {
  name: 'ContractList',
  components: { Pagination },
  data() {
    return {
      dialogFormVisible1:false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      special_id:'',
      errStr:'',
      description:'',
      fileLength:0,
      nowNum:0,
      errNum:0,
      class_options:[],
      edit_class:[],
      content: '',
      imageUrl: '',
      imageUrl1: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: '',
        type:'id',
        class_id:[],
        status:'success',
        ext:'',
        time:[],
        sort_type:"desc",
        special_id:'',
        banner_special_id: ''
      },
      specialList:[],
      dialogFormVisible: false,
      dialogBannerVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      class_id: [],
      showBannerUrl: '',
      temp: {
        id: undefined,
        class_id: [],
        title: '',
        download: '',
        special_id:'',
        banner_special_id:''
      },
      fileList:[],
      options: [{
        value: 'doc',
        label: 'doc'
      }, {
        value: 'docx',
        label: 'docx'
      }, {
        value: 'other',
        label: 'other'
      }],
      banner_special_id:'',
      rules: {
        title: [{ required: true, message: '标题不能为空' }]
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],

      }

    }
  },
  watch: {
    // imageUrl: {
    //   deep: true,
    //   handler(val) {
    //   }
    // },
    // imageUrl1: {
    //   deep: true,
    //   handler(val) {
    //   }
    // }
  },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 16) {
        return value.slice(0, 16) + '...'
      }
      return value
    }

  },
  created() {
    const special_id = parseInt(this.$route.query.special_id)
    if(special_id){
      this.listQuery.special_id = special_id
    }
    this.getNewClass()
    this.getList()
    this.getSpecial()
  },
  methods: {
    get_ocpc(){
      this.dialogFormVisible1 = true;
      this.banner_special_id =''
    },
    bindSpecial(){
      bindSpecial(this.listQuery,this.banner_special_id).then(response=>{
          if(response.code == 200){
            this.$notify({
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible1 = false
            this.getList()
          }
      })
    },
    handleClickExport() {
      if(this.listQuery.class_id.length > 0 || this.listQuery.title != '' || this.listQuery.time.length > 0){
        let search = JSON.stringify(this.listQuery)
        window.open('/api/excel/export_contract?search='+search)
      }else{
        this.$message.info('请先选择下载条件');
      }
    },
    getSpecial(){
      getAll().then(response=>{
          this.specialList = response.data
      })
    },
    getNewClass() {
      getNewClass().then(response => {
        this.class_options = response.data// Just to simulate the time of the request
      })
    },
    changeClass(val){

    },
    getList() {
      this.listLoading = true
      this.listQuery.class_id = JSON.stringify(this.listQuery.class_id)
      getList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        // Just to simulate the time of the request
        this.listLoading = false
        this.listQuery.class_id = JSON.parse(this.listQuery.class_id)
      })
    },
    toUrl(id){
      let uri = 'https://www.wenhetong.com/contractdetail/'+id+'.html'
      window.open(uri)
    },
    handleMake(row){
        makePic(row.id).then(response=>{
            if(response.code == 200){
              this.$message.success(response.msg)
              this.getList()
            }
        })
    },
    handleMakePng(row){
      makePng(row.id).then(response=>{
        if(response.code == 200){
          this.$message.success(response.msg)
          this.getList()
        }
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title:'',
        download:'',
        special_id: '',
        banner_special_id: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.temp.url || !this.temp.thumb) {
            this.$message.error('请先上传图片')
            return ''
          }
          if (!this.temp.type) {
            this.$message.error('请先选择类型')
            return ''
          }
          createBanner(this.temp).then(response => {
            if (response.code == 200) {
              this.dialogFormVisible = false
              this.$notify({
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },
    handleUpdate(row){
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if(row.special_id > 0){
        this.temp.special_id = row.special_id
      }else{
        this.temp.special_id = ''
      }
      parentClass(row.class_id).then(response=>{
          this.edit_class = response.data
      })
      getStatus().then(response=>{
        if(response.data){
          this.description = response.data.desc.replaceAll('{title}',row.title)
        }
      })

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.class_id = this.edit_class
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(response => {
            if (response.code == 200) {
              this.dialogFormVisible = false
              this.$notify({
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },

    handleChange(file, fileList) {
      this.fileLength = fileList.length
    },
    handleSuccess(res, file, fileList) {
       if (res.code == 200) {
         this.nowNum++
       } else {
         this.errStr += file.name+'<br/>'
         this.errNum++
         this.nowNum++
        // this.$notify({
        //   title: '消息',
        //   type: 'error',
        //   message: '上传失败',
        //   duration: 2000
        // })
      }
      if(fileList.length == this.nowNum){

        this.$notify({
          title: '消息',
          dangerouslyUseHTMLString: true,
          type: 'success',
          duration: 0,
          message: '上传结束<br/>'+'失败个数:'+this.errNum+'<br/>'+
            this.errStr
        })
        this.nowNum = 0
        this.errNum = 0
        this.errStr = ''
        this.$refs.upload.clearFiles()
        this.getList()
      }
    },

    handleError(err, file, fileList){
        // this.nowNum++
        // this.errNum++
    },
    beforeUpload(file) {
       // const isWord = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
       // const isPdf = file.type === 'application/pdf'
       const isLt10M = file.size / 1024 / 1024 < 10
      if(this.edit_class.length <= 0){
        this.$message.error('请先选择分类')
        return false
      }
      // if (!isWord && !isPdf) {
      //   this.$message.error('上传图片只能是 pdf/docx 格式!')
      //   return false
      // }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
     return true
    },

    handleDelete(row, index) {
      this.$confirm(
        '确定要删除该条数据吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
        del(row.id).then(response => {
          if (response.code == 200) {
            this.list.splice(index, 1)
            this.$notify({
              message: response.msg,
              type: 'success',
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    showBanner(url) {
      this.showBannerUrl = url
      this.dialogBannerVisible = true
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
